using UnityEngine;
using UnityEditor;

namespace LCH
{
    /// <summary>
    /// 网格绘制器 - 材质相关功能模块
    /// </summary>
    public partial class LchMeshPainter
    {
        /// <summary>
        /// 选择对象改变时的处理
        /// </summary>
        void OnSelectObjectChange()
        {
            selectMeshObjectRender = null;
            selectObjectMaterial = null;
            
            // 清除控制图管理器缓存
            if (controlTextureManager != null)
            {
                controlTextureManager.ClearCache();
            }

            // 清空控制图数组
            ControlTextureOperations.ClearControlTextures(ctrlText, editorCtrl1RT);
            
            DrawUV();
            SetDefaultBrushSize();
        }
        
        /// <summary>
        /// 绘制UV预览
        /// </summary>
        void DrawUV()
        {
            var mesh = selectObject.sharedMesh;
            
            if (uvMark == UVMark.UV1)
            {
                if (mesh.uv2.Length == 0)
                {
                    EditorUtility.DisplayDialog(Languages.GetValue( 36,"Not uv1 on mesh"), Languages.GetValue(36, "Not uv1 on mesh"), Languages.GetValue(35, "ok"));
                    uvMark = UVMark.UV0;
                }
                else
                {
                    uvAreaPerviewTexture.DrawUVs(mesh.uv2, mesh.triangles);
                    return;
                }
                
            }
            if (uvMark == UVMark.UV2)
            {
                if (mesh.uv2.Length == 0)
                {
                    EditorUtility.DisplayDialog(Languages.GetValue(37, "Not uv2 on mesh"), Languages.GetValue(37, "Not uv2 on mesh"), Languages.GetValue(35, "ok"));
                    uvMark = UVMark.UV0;
                }
                else
                {
                    uvAreaPerviewTexture.DrawUVs(mesh.uv2, mesh.triangles);
                    return;
                }
            }
            uvAreaPerviewTexture.DrawUVs(mesh.uv, mesh.triangles);
        }
        
        /// <summary>
        /// 从材质中重放指定索引的控制图
        /// </summary>
        /// <param name="index">控制图索引</param>
        void ReplayCtrlTexture(int index)
        {
            ControlTextureOperations.ReplayControlTextureFromMaterial(
                selectObjectMaterial, 
                index, 
                detectedCtrlTextureNames, 
                ref ctrlText);
        }
        
        /// <summary>
        /// 从材质中重放所有控制图
        /// </summary>
        void ReplayAllControlTextures()
        {
            ControlTextureOperations.ReplayAllControlTextures(
                selectObjectMaterial, 
                detectedCtrlTextureNames, 
                ref ctrlText);
        }
        
        /// <summary>
        /// 重放第一张控制图（向后兼容方法）
        /// </summary>
        void ReplayCtrl1Texture()
        {
            if (detectedCtrlTextureNames.Count > 0)
                ReplayCtrlTexture(0);
        }
        
        /// <summary>
        /// 重放第二张控制图（向后兼容方法）
        /// </summary>
        void ReplayCtrl2Texture()
        {
            if (detectedCtrlTextureNames.Count > 1)
                ReplayCtrlTexture(1);
        }
        
        /// <summary>
        /// 从材质中重放FlowMap纹理
        /// </summary>
        void ReplayFlowTexture()
        {
            // flowmap在最后一张控制图的Alpha通道，不需要单独获取
            // 但如果shader中有独立的flowmap属性，也支持
            if (selectObjectMaterial.HasProperty(setting.flowMapTextureName))
            {
                Texture t = selectObjectMaterial.GetTexture(setting.flowMapTextureName);
                if (t is Texture2D)
                {
                    flowMapTex = (Texture2D)t;
                }
            }
        }
        
        /// <summary>
        /// 材质改变时的处理
        /// </summary>
        /// <param name="old">旧的材质</param>
        void OnMaterialChange(Material old)
        {
            // 保存旧材质的控制图
            if (null != old && ctrlText != null)
            {
                ControlTextureOperations.ApplyControlTexturesToMaterial(old, ctrlText, detectedCtrlTextureNames);
            }
            
            // 清空控制图数组（不释放资源）
            ControlTextureOperations.ClearControlTextures(ctrlText, editorCtrl1RT);

            // 检测新的控制图
            if (selectObjectMaterial != null && selectObjectMaterial.shader != null)
            {
                DetectControlTextures(selectObjectMaterial.shader);
                CheckIconArray();
                
                // 重放所有检测到的控制图
                ReplayAllControlTextures();
            }
            
            if (hasFlowMap)
            {
                Debug.LogError("flow map init");
                ReplayFlowTexture();
            }
            
            texturePaninnerUndoRedo.Clear();
            // 检查是否有任何控制图
            bool hasAnyCtrl = false;
            if (ctrlText != null)
            {
                for (int i = 0; i < ctrlText.Length; i++)
                {
                    if (ctrlText[i] != null)
                    {
                        hasAnyCtrl = true;
                        break;
                    }
                }
            }
            if (hasAnyCtrl)
            {
                texturePaninnerUndoRedo.AddAll(ctrlText, flowMapTex);
            }
             

            if (null != selectObjectMaterial)
            {
                if (selectObjectMaterial.IsKeywordEnabled("_CHANNEL_UV2"))
                {
                    uvMark = UVMark.UV2;
                }
                else if (selectObjectMaterial.IsKeywordEnabled("_CHANNEL_UV1"))
                {
                    uvMark = UVMark.UV1;
                }
                else
                {
                    uvMark = UVMark.UV0;
                }
            }
        }
    }
}

